package com.vhly.superrecoder;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: nnn
 * Date: 2010-11-25
 * Time: 14:42:17
 */
public final class MainActivity extends Activity implements AdapterView.OnItemLongClickListener, AdapterView.OnItemClickListener, View.OnClickListener {

    public static final int GRP_MENU = 0;

    public static final int MNU_RECORD = 0;
    public static final int MNU_STOP = 1;
    public static final int MNU_SETTING = 2;


    private ListView lstView;
    private List<Map<String, String>> records;

    private static final String[] keys = {"rtl", "rty", "rti"};
    private static final int[] ids = {R.id.rdtitle, R.id.rdtype, R.id.rdtime};
    private SimpleAdapter adapter;


    // Record

    private static MediaRecorder recorder;

    private static SharedPreferences preferences;

    private Intent intentSetting;

    // end

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        lstView = new ListView(this);
//        records = new ArrayList<Map<String, String>>();
//        HashMap<String, String> map = new HashMap<String, String>();
//        map.put(keys[0], "TT");
//        map.put(keys[1], "TT");
//        map.put(keys[2], "TT");
//        records.add(map);
//        adapter = new SimpleAdapter(this, records, R.layout.records, keys, ids);
//        lstView.setAdapter(adapter);
//        lstView.setOnItemLongClickListener(this);
//        lstView.setOnItemClickListener(this);
//        setContentView(lstView);
        setContentView(R.layout.main);
        if(preferences == null){    // 830059037000
            preferences = getSharedPreferences("SRSettings",Context.MODE_WORLD_WRITEABLE);
        }

        Button btnRecord = (Button) findViewById(R.id.btnstart);
        if(btnRecord != null){
            btnRecord.setOnClickListener(this);
        }
        Button btnPause = (Button) findViewById(R.id.btnpause);
        if(btnPause != null){
            btnPause.setOnClickListener(this);
        }
        Button btnStop = (Button) findViewById(R.id.btnstop);
        if(btnStop != null){
            btnStop.setOnClickListener(this);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.addSubMenu(GRP_MENU, MNU_RECORD, MNU_RECORD, R.string.mnu_record);
        menu.addSubMenu(GRP_MENU, MNU_STOP, MNU_STOP, R.string.mnu_stop);
        menu.addSubMenu(GRP_MENU, MNU_SETTING, MNU_SETTING, R.string.mnu_setting);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case MNU_RECORD:
                startRecord();
                break;
            case MNU_STOP:
                stopRecord();
                break;
            case MNU_SETTING:
                if(intentSetting == null){
                    intentSetting = new Intent(this, SettingActivity.class);
                }
                startActivity(intentSetting);
                break;
        }
        return true;
    }

    /**
     * Start Record
     */
    private void startRecord() {
        boolean silent = preferences.getBoolean("silent",false);
        System.out.println("silent = " + silent);
        recorder = new MediaRecorder();
        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        recorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR);
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        try {
            File storageDirectory = Environment.getExternalStorageDirectory();
            if (storageDirectory != null) {
                File of = new File(storageDirectory, "SuperRecorder");
                of.mkdirs();
                String s = of.getAbsolutePath();
                Calendar cal = Calendar.getInstance();
                int year = cal.get(Calendar.YEAR);
                int month = cal.get(Calendar.MONTH) + 1; // from 0 to 11
                int day = cal.get(Calendar.DAY_OF_MONTH);
                int hour = cal.get(Calendar.HOUR_OF_DAY);
                int min = cal.get(Calendar.MINUTE);
                int sec = cal.get(Calendar.SECOND);
                StringBuffer sb = new StringBuffer(s);

                sb.append('/').append(year);
                if(month < 10){
                    sb.append('0');
                }
                sb.append(month);
                if(day < 10){
                    sb.append('0');
                }
                sb.append(day);
                if(hour < 10){
                    sb.append('0');
                }
                sb.append(hour);
                if(min < 10){
                    sb.append('0');
                }
                sb.append(min);
                if(sec < 10){
                    sb.append('0');
                }
                sb.append(sec);
                sb.append(".amr");
                recorder.setOutputFile(sb.toString());
                sb = null;

                recorder.prepare();
                recorder.start();
                NotificationManager manager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
                Notification notification = new Notification(R.drawable.ic_26_btn_record, getString(R.string.recording), System.currentTimeMillis());

                Intent intent = new Intent(this, MainActivity.class);
                PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
                notification.setLatestEventInfo(this, getString(R.string.recording), getString(R.string.recording), pendingIntent);

                manager.notify(10, notification);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void stopRecord() {
        try {
            recorder.stop();
            recorder.release();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {

        return false;
    }

    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
    }

    public void onClick(View view) {
        int id = view.getId();
        switch(id){
            case R.id.btnstart:
                startRecord();
                break;
            case R.id.btnpause:
                break;
            case R.id.btnstop:
                stopRecord();
                break;

        }
    }
}

